package com.zlm.fork;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @Author: 郑
 *如何使用forkjoin
 * 1 forkjoinPool 执行
 * 2 计算任务 forkjoinPool.execute(ForkjoinTask task)
 * 3 计算类必须继承RecursiveTask<>
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;

    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if(end -start > temp){
            //forkjoin
            long middle = (start+end)/2;//中间值
            ForkJoinDemo forkJoinDemo = new ForkJoinDemo(start, middle);
            forkJoinDemo.fork();//拆分任务，把任务压入线程队列
            ForkJoinDemo forkJoinDemo1 = new ForkJoinDemo(middle + 1, end);
            forkJoinDemo1.fork();
            long sum = forkJoinDemo.join() + forkJoinDemo1.join();
            return sum;
        }else{
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum +=i;
            }
            return sum;
        }

    }
    public static Long test1(){
        long start = System.currentTimeMillis();
        Long sum = 0L;
        for (Long i = 1L; i <= 10_0000_0000; i++) {
            sum +=i;
        }
        return sum;

    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        //Long sum =test1();//8524
//        ForkJoinPool joinPool = new ForkJoinPool();
//          submit提交任务
//        ForkJoinTask<Long> submit = joinPool.submit(new ForkJoinDemo(1L, 10_0000_0000L));
//        Long sum = submit.get();//6853
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0L, Long::sum);//553
        long end = System.currentTimeMillis();
        System.out.println(sum +"===时间===》"+(end-start));
    }


}

